import { ElButton, ElDialog, ElSpace } from 'element-plus'
import { computed, defineComponent, reactive, toRef, toRefs } from 'vue'
import { useRoute } from 'vue-router'
import { VxeGrid } from 'vxe-table'

import { roleApi } from '@/apis'
import {
  type GridExtOptions,
  TABLE_FORMAT,
  TABLE_ITEM_RENDER,
  TABLE_RENDERER,
  useGridExt
} from '@/hooks'

export default defineComponent({
  name: 'AddUserDialog',
  emits: ['success'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      submitLoading: false,
      selectedIds: new Set<string>(),
      gridConfig: {
        showOverflow: true,
        formConfig: {
          items: [
            {
              field: 'userName',
              title: '用户名称',
              itemRender: {
                name: TABLE_ITEM_RENDER.Input,
                props: {
                  placeholder: '请输入用户名称'
                }
              }
            },
            {
              field: 'phone',
              title: '手机号',
              itemRender: {
                name: TABLE_ITEM_RENDER.Input,
                props: {
                  placeholder: '请输入手机号'
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columns: [
          { type: 'checkbox', width: 50 },
          {
            field: 'userName',
            title: '用户名称'
          },
          {
            field: 'nickName',
            title: '用户昵称'
          },
          {
            field: 'email',
            title: '邮箱'
          },
          {
            field: 'phone',
            title: '手机'
          },
          {
            field: 'status',
            title: '状态'
          },
          {
            field: 'createTime',
            title: '创建时间',
            formatter: TABLE_FORMAT.Date,
            width: 190
          }
        ],
        pagerConfig: {
          background: true,
          layouts: [
            'PrevJump',
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total'
          ],
          pageSize: 15
        },
        proxyConfig: {
          autoLoad: false,
          seq: true,
          form: true,
          props: {
            result: 'list',
            total: 'total'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await roleApi.getUnallocatedPage(
                route.params.id as string,
                {
                  pageSize: page.pageSize,
                  pageNum: page.currentPage,
                  ...form
                }
              )
              return data
            }
          }
        },
        onCheckboxChange({ checked, row }) {
          checked
            ? state.selectedIds.add(row.id)
            : state.selectedIds.delete(row.id)
        }
      } as GridExtOptions
    })

    const route = useRoute()
    const gridExtHook = useGridExt(toRef(state, 'gridConfig'))

    const roleId = computed(() => route.params.id as string)

    function open() {
      state.show = true
      gridExtHook.refresh()
    }

    function handleClose() {
      state.show = false
    }

    async function handleSubmit() {
      try {
        state.submitLoading = true
        await roleApi.allocate(roleId.value, {
          ids: Array.from(state.selectedIds)
        })
        state.submitLoading = false
        state.selectedIds.clear()
        handleClose()
        emit('success')
      } catch {
        state.submitLoading = false
      }
    }

    return {
      ...toRefs(state),
      gridRef: gridExtHook.gridRef,
      open,
      handleClose,
      handleSubmit
    }
  },
  render() {
    return (
      <ElDialog
        v-model={this.show}
        title="添加用户"
        width="800px"
        beforeClose={this.handleClose}
        destroyOnClose
      >
        {{
          default: () => (
            <VxeGrid
              ref={(e: any) => (this.gridRef = e)}
              {...this.gridConfig}
            ></VxeGrid>
          ),
          footer: () => (
            <ElSpace>
              <ElButton onClick={this.handleClose}>取消</ElButton>
              <ElButton
                type="primary"
                loading={this.submitLoading}
                onClick={this.handleSubmit}
              >
                确定
              </ElButton>
            </ElSpace>
          )
        }}
      </ElDialog>
    )
  }
})
